/*
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2025-04-13 14:31:53
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2025-04-13 14:41:51
 * @FilePath: \leemvvm\lee-mvvm\src\core\reactivity\watch.ts
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
import { effect } from "./effect";

export function watch(
  source: () => any,
  cb: (newVal: any, oldVal: any) => void
) {
  let oldValue: any;
  effect(() => {
    const newValue = source();
    if (newValue !== oldValue) {
      cb(newValue, oldValue);
      oldValue = newValue;
    }
  });
}

// export function watch<T>(
//   getter: () => T,
//   callback: (newVal: T, oldVal: T) => void
// ) {
//   let oldValue: T;

//   // 创建一个带有返回值的副作用函数
//   const runner = () => {
//     const newValue = getter();
//     if (newValue !== oldValue) {
//       callback(newValue, oldValue);
//       oldValue = newValue;
//     }
//   };

//   // 初始化获取一次旧值，并设置响应式监听
//   effect(() => {
//     oldValue = getter();
//   });

//   // 再次建立一个监听，用于实际变化时触发 callback
//   effect(runner);
// }
